<template>
	<view class="content">
		<button class="auth-container" v-if="openauth" open-type="getPhoneNumber"
			@getphonenumber="getPhoneNumber"></button>
		<Tabbar :page="tab"></Tabbar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tab: '',
				openauth:false,
			}
		},
		onShow() {
			this.tab = "/pages/my/index"
			let get_phone = uni.getStorageSync('phone')
			if (get_phone.length == 11) {
				this.openauth = false;
			} else {
				this.get_code();
			}
			let is_phone = uni.getStorageSync('is_phone')
			console.log(is_phone,'是否弹授权')
			if(is_phone===false){
				this.openauth  = false;
			}
		},
		methods: {
			get_code() {
				let _this = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						//loginRes中有code，拿着code再请求自己服务器以获取openid
						_this.$request.request({
							url: 'api/ser/xcx/get_open',
							data: {
								'code': loginRes.code
							},
						}).then(res => {
							if (res.code == 1) {
								uni.setStorageSync('openid', res.data.openid)
								uni.setStorageSync('sessionKey', res.data.session_key)
								uni.setStorageSync('unionid', res.data.unionid)
								if (res.data.phone != '' && res.data.phone != null) {
									console.log(res.data.phone.length, '手机号长度')
									if (res.data.phone.length == 11) {
										uni.setStorageSync('phone', res.data.phone)
										_this.openauth = false;
									} else {
										uni.removeStorageSync('phone');
									}
								} else {
									uni.removeStorageSync('phone');
								}
							} else {
								uni.removeStorageSync('phone');
								uni.removeStorageSync('openid');
								uni.removeStorageSync('sessionKey');
								uni.removeStorageSync('unionid');
							}
						})
					}
				});
			},
			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") { //同意授权
					let data = {}
					data.encryptedData = e.detail.encryptedData;
					data.iv = e.detail.iv;
					data.openid = uni.getStorageSync('openid');
					data.sessionKey = uni.getStorageSync('sessionKey');
					this.$request.request({
						url: 'api/ser/xcx/getMobile',
						data: data,
					}).then(res => {
						if (res.code == 1) {
							uni.setStorageSync('phone', res.data)
							this.openauth = false;
						} else {
							this.get_code()
						}
					})
				} else {
					this.openauth  = false;
					uni.setStorageSync('is_phone',false);
				}
			},
					
		}
	}
</script>

<style>
.content{
	min-height: 100vh;
}
</style>
